<?php
/**
 * Created by PhpStorm.
 * User: sen
 * Date: 16/7/12
 * Time: 上午10:26
 */
namespace app\controllers;
use yii\web\Controller;

require_once('vendor/upyun.class.php');
include_once('vendor/Uploader.class.php');

use app\models\Category;
use app\models\Attr;
use app\models\User;
use app\models\Attr_opt;
use app\models\Commodity;
use app\models\Postage_template;
use app\models\Postage_template_detail;

use yii\filters\AccessControl;
use yii\filters\VerbFilter;


class PublishController extends Controller{


    public function init(){
        $this->enableCsrfValidation = false;
        if(!\Yii::$app->user->id){
            $url = \Yii::$app->request->getPathInfo();
            return $this->redirect('../login/index?url='.$url);
       }
        $userId = \Yii::$app->user->id;
        $user = new User();
        $admin = $user->findIdentity($userId);
        if($admin['type']==1 or $admin['type']==0){
            return $this->redirect('../login/logout');
        }
    }

    //加载默认页面
    public function actionIndex(){
        $view = \Yii::$app->view;
        $view->params['menuitemid']=21;
        return $this->render('index');
    }

    //获取一级分类目录
    public function actionFirstCategoryList(){
        $categoryModel = new Category();
        $rs = $categoryModel->getFirstCategoryList();
        echo json_encode($rs);
    }

    //获取二级分类目录
    public function actionSecondCategoryList(){
        //获取pid字段
        $request = \Yii::$app->request;
        $id = $request->get('pid');
        $categoryModel = new Category();
        $rs = $categoryModel->getSecondCategoryList($id);
        echo json_encode($rs);
    }

    //新增一二分类分类
    public function actionAddSecondCategory(){
        //获取pid字段
        $request = \Yii::$app->request;
        $pid = $request->get('pid');
        $category_name= $request->get('category_name');
        $create_time = date('Y-m-d H:i:s');
        $categoryModel = new Category();
        $categoryModel->pid=$pid;
        $categoryModel->category_name=$category_name;
        $categoryModel->create_time=$create_time;

        if($categoryModel->save() > 0){
            $rs = $categoryModel->getSecondCategoryList($pid);
            echo json_encode($rs);
        } else{
            echo json_encode('0');
        }
    }

    //根据分类id获取属性列表
    public function actionGetAttrListByCategoryId(){
        //获取category_id字段
        $request = \Yii::$app->request;
        $category_id = $request->get('category_id');
        $attrModel = new Attr();
        $rs = $attrModel->getAttrList($category_id);
        echo json_encode($rs);
    }

    //根据属性id获取已有属性列表
    public function actionGetAttrOptListByAttrId(){
        //获取attr_id字段
        $request = \Yii::$app->request;
        $attr_id = $request->get('attr_id');
        $attrOptModel = new Attr_opt();
        $rs = $attrOptModel->getAttrOptList($attr_id);
        echo json_encode($rs);
    }

    //添加属性
    public function actionAddAttr(){
        //获取category_id字段
        $request = \Yii::$app->request;
        $category_id = $request->get('category_id');
        $create_time = date('Y-m-d H:i:s');
        $attr_name = $request->get('attr_name');

        $attrModel = new Attr();
        $attrModel->category_id=$category_id;
        $attrModel->attr_name=$attr_name;
        $attrModel->create_time=$create_time;
        if($attrModel->save() > 0){
            echo \Yii::$app->db->getLastInsertID();
        } else{
            echo json_encode('0');
        }
    }

    //添加具体属性值
    public function actionAddAttrOpt(){
        //获取attr_id字段
        $request = \Yii::$app->request;
        $attr_id = $request->get('attr_id');
        $create_time = date('Y-m-d H:i:s');
        $attr_opt_name = $request->get('attr_opt_name');

        $attrOptModel = new Attr_opt();
        $attrOptModel->attr_id=$attr_id;
        $attrOptModel->attr_opt_name=$attr_opt_name;
        $attrOptModel->create_time=$create_time;
        if($attrOptModel->save() > 0){
            echo \Yii::$app->db->getLastInsertID();
        } else{
            echo json_encode('0');
        }
    }

    //删除属性
    public function actionRemoveAttr(){
        //获取category_id字段
        $request = \Yii::$app->request;
        $attr_id = $request->get('attr_id');
        //删除标志位
        Attr::updateAll(['del_flag'=>'0'],['attr_id'=>$attr_id]);
    }

    //删除属性
    public function actionRemoveAttrOpt(){
        //获取attr_opt_id字段
        $request = \Yii::$app->request;
        $attr_opt_id = $request->get('attr_opt_id');
        //删除标志位
        Attr_opt::updateAll(['del_flag'=>'0'],['attr_opt_id'=>$attr_opt_id]);
    }

    //发布属性
    public function actionPublish(){
        //获取attr_id字段
        $request = \Yii::$app->request;
        $store_id = $request->post('store_id');
        $price = $request->post('price');
        $pic_url = $request->post('pic_url');
        $banner_url = $request->post('banner_url');
        $is_hot = $request->post('is_hot');
        $commodity_name = $request->post('commodity_name');
        $content = $request->post('content');
        $content_true = $request->post('content_true');
        $first_category = $request->post('first_category');
        $second_category = $request->post('second_category');

        $attr_opt_id = $request->post('attr_opt_id');
        $pro_id= $request->post('pro_id');
        $is_sale = $request->post('is_sale');
        $stock_num = $request->post('stock_num');
        $create_time = date('Y-m-d H:i:s');
        $postage_template_id = $request->post('postage_template_id');

        $commodityModel = new Commodity();
        $commodityModel->store_id=$store_id;
        $commodityModel->price=$price;
        $commodityModel->pic_url=$pic_url;
        $commodityModel->banner_url=$banner_url;
        $commodityModel->is_hot=$is_hot;
        $commodityModel->commodity_name=$commodity_name;
        $commodityModel->content=$content;
        $commodityModel->content_true=$content_true;
        $commodityModel->first_category=$first_category;
        $commodityModel->second_category=$second_category;
        $commodityModel->attr_opt_id=$attr_opt_id;
        $commodityModel->pro_id=$pro_id;
        $commodityModel->is_sale=$is_sale;
        $commodityModel->stock_num=$stock_num;
        $commodityModel->create_time=$create_time;
        $commodityModel->postage_template_id=$postage_template_id;
        if($commodityModel->save() > 0){
            echo \Yii::$app->db->getLastInsertID();
        } else{
            echo json_encode('0');
        }
    }


    //重新编辑商品
    public function actionEditCommodity(){

        $request = \Yii::$app->request;
        $commodity_id = $request->get('commodity_id');
        $sale = $request->get('sale');

        if(!$commodity_id){
//            echo '2222';
            return $this->redirect('index');
        }

        //需要加这个 防止服务端报错
        $view = \Yii::$app->view;
        if($sale==1){
            $view->params['menuitemid']=22;
        }else{
            $view->params['menuitemid']=23;
        }

        $model=Commodity::find()->where(['commodity_id'=>$commodity_id])->one();
        $postage_template = Postage_template::find()->where(['id'=>$model->postage_template_id, 'del_flag'=>1])->one();
        if ($postage_template!=null) {
            $postage_template_name = $postage_template->name;
        } else {
            $postage_template_name = '';
            $model->postage_template_id = '';
        }
        return $this->render('edit',[
            "model" => $model, "postage_template_name" => $postage_template_name]);
    }

    //修改属性
    public function actionEdit(){

        //获取attr_id字段
        $request = \Yii::$app->request;
        $commodity_id = $request->post('commodity_id');//获取id
        $store_id = $request->post('store_id');
        $price = $request->post('price');
        $pic_url = $request->post('pic_url');
        $banner_url = $request->post('banner_url');
        $is_hot = $request->post('is_hot');
        $commodity_name = $request->post('commodity_name');
        $content = $request->post('content');
        $content_true = $request->post('content_true');
        $first_category = $request->post('first_category');
        $second_category = $request->post('second_category');

        $attr_opt_id = $request->post('attr_opt_id');
        $pro_id= $request->post('pro_id');
        $is_sale = $request->post('is_sale');
        $stock_num = $request->post('stock_num');
        $postage_template_id = $request->post('postage_template_id');
        $create_time = date('Y-m-d H:i:s');
        $rs = \Yii::$app->db->createCommand()->update('hcps_commodity', [
            'commodity_name' => $commodity_name,
            'content' => $content,
            'store_id' => $store_id,
            'price' => $price,
            'is_hot' => $is_hot,
            'pic_url' => $pic_url,
            'banner_url' => $banner_url,
            'content_true' => $content_true,
            'first_category' => $first_category,
            'second_category' => $second_category,
            'attr_opt_id' => $attr_opt_id,
            'pro_id' => $pro_id,
            'is_sale' => $is_sale,
            'stock_num' => $stock_num,
            'create_time' => $create_time,
            'postage_template_id' => $postage_template_id
        ], "commodity_id=:commodity_id", [
            ':commodity_id' => $commodity_id
        ])->execute();
        echo $rs;
    }

    public function actionPostageTemplateList()
    {
        $postageTemplateModel = new Postage_template();
        $rs = $postageTemplateModel->getAll();
        echo json_encode($rs);
    }

    public function actionAddPostageTemplate()
    {
        $request = \Yii::$app->request;
        $name = $request->post('name');

        $model = new Postage_template();
        $model->name=$name;
        $model->default_unit_price=0.00;
        if($model->save() > 0){
            $model->id=\Yii::$app->db->getLastInsertID();
            echo json_encode([
                "id" => $model->id,
                "name" => $model->name,
                "default_unit_price" => $model->default_unit_price,
            ]);
        } else{
            echo json_encode('0');
        }
    }

    public function actionDeletePostageTemplate()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        if (Commodity::find()->where(['postage_template_id'=>$id])->exists()) {
            echo json_decode(["status"=>"failed", "message"=>"不能删除已经被使用的运费模板!"]);
        }
        else {
            Postage_template::updateAll(['del_flag'=>'0'],['id'=>$id]);
            echo json_encode(["status"=>"success"]);
        }
    }

    public function actionEditPostageTemplate()
    {
        $request = \Yii::$app->request;
        $id = $request->post('id');
        $insertData = $request->post('insertData');
        $deleteData = $request->post('deleteData');
        if ($insertData == null && $deleteData == null) {
            echo json_encode(["status"=>"succeed", "message"=>"没有更新"]);
            return;
        }
        if (!$this->validateTemplateDetails($insertData)){
            echo json_encode(["status"=>"failed", "message"=>"填写信息有误,请检查"]);
            return;
        }
        $templateDetails = [];
        $templateDetailsToDelete = [];
        $defaultUnitPrice = 0.00;
        $isDefaultUnitPriceSet = false;
        if ($insertData != null) {
            foreach ($insertData as $item) {
                if ($item["province_name"] == "全国") {
                    $isDefaultUnitPriceSet = true;
                    $defaultUnitPrice = $item["unit_price"];
                } else {
                    $templateDetail = Postage_template_detail::find()->where(['postage_template_id'=>$id,
                        "province_name"=>$item["province_name"]])->one();
                    if ($templateDetail == null) {
                        $templateDetail = new Postage_template_detail();
                    }
                    $templateDetail->postage_template_id = $id;
                    $templateDetail->province_name = $item["province_name"];
                    $templateDetail->unit_price = $item["unit_price"];
                    array_push($templateDetails, $templateDetail);
                }
            }
        }
        if ($deleteData != null) {
            foreach ($deleteData as $item) {
                if ($item["province_name"] == "全国") {
                    $isDefaultUnitPriceSet = true;
                    $defaultUnitPrice = 0.00;
                } else {
                    $templateDetail = Postage_template_detail::find()->where(['postage_template_id'=>$id,
                        "province_name"=>$item["province_name"]])->one();
                    array_push($templateDetailsToDelete, $templateDetail);
                }
            }
        }
        $model = new Postage_template();
        $connection=\Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
            if ($isDefaultUnitPriceSet) {
                Postage_template::updateAll(['default_unit_price'=>$defaultUnitPrice],['id'=>$id]);
            }
            foreach ($templateDetailsToDelete as $templateDetail) {
                $templateDetail->delete();
            }
            foreach ($templateDetails as $templateDetail) {
                $templateDetail->save();
            }
            echo json_encode(["status"=>"succeed", "message"=>"succeed"]);
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            echo json_encode(["status"=>"failed", "message"=>$e.getMessage()]);
        }
        return;
    }

    private function validateTemplateDetails($data) {
        $provinces = [];
        if ($data != null) {
            foreach ($data as $item) {
                foreach(explode('\.',$item["province_name"]) as $province) {
                    if (array_search($province, $provinces)) {
                        return false;
                    }
                    else {
                        array_push($provinces, $province);
                    }
                }
            }
        }
        return true;
    }

    public function actionGetPostageTemplateDetail()
    {
        $request = \Yii::$app->request;
        $template_id = $request->post('template_id');
        $model=Postage_template_detail::find()->where(['postage_template_id'=>$template_id])->all();
        $rows = [];
        foreach ($model as $item) {
            array_push($rows, ["province_name"=>$item->province_name, "unit_price"=>number_format($item->unit_price,2)]);
        }
        echo json_encode([
            "total" => count($model),
            "rows"=>$rows]);
    }

    public function actionGetAllProvince(){
        $result=\Yii::$app->db->createCommand('SELECT name FROM hcps_province')->queryAll();
        echo json_encode($result);
    }

    //上传图片
    public function actionPostimg(){
        echo $_POST['filed'];
    }

}